package com.remote.ems.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.plf.common.domain.ResponseDTO;
import com.remote.ems.api.Ems_Feign;
import com.remote.ems.model.enums.EmsStatusEnum;
import com.remote.ems.model.vo.EmsTrackVO;
import com.remote.ems.utils.CryptoThirdSM4Tools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author xiongzhiwen
 * @version 1.0
 * @description: 邮政controller
 * @date 2024/3/15 15:19
 */
@RestController
@Slf4j
public class EmsController {

    /**
     * emsFeign
     */
    @Resource
    private Ems_Feign emsFeign;
    /**
     * 测试协议客户号
     */
    @Value("${ems.senderNo:#{null}}")
    private String senderNo;
    /**
     * 测试授权码
     */
    @Value("${ems.authorization:#{null}}")
    private String authorization;
    /**
     *测试签名钥匙
     */
    @Value("${ems.key:#{null}}")
    private String key;
    /**
     * 拼接变量模板
     */
    private static final String BILLNO_STR = "{\"waybillNo\" : %s}";

    /**
     * APICODE_EMSTRACE 快递单号记录查询
     */
    private static final String APICODE_EMSTRACE = "040001";


    /**
     * @description: 查询对应快递单号的快递轨迹
     * @date: 2024/3/15 15:30
     * @param: [billNo] : 快递单号
     * @return: EmsTrackVO
     */
    @GetMapping("/ems/emsTraceDetail")
    public ResponseDTO emsTraceDetail(@RequestParam("billNo") String billNo) {
        StringBuffer buffer = new StringBuffer();
        final String billNoStr = String.format(BILLNO_STR, billNo);
        buffer.append(billNoStr).append(this.key);
        String sm4Encrypt = CryptoThirdSM4Tools.sm4Encrypt(buffer.toString(), key);
        log.warn("sm4Encrypt: {} " , sm4Encrypt);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeStamp = sdf.format(new Date());
        JSONObject result = emsFeign.emsTraceDetail(senderNo,APICODE_EMSTRACE,authorization,timeStamp,sm4Encrypt);
        if (result.get("retCode").equals(EmsStatusEnum.SUCCESS.getStatus())) {
            JSONObject retBody = result.getJSONObject("retBody");
            if (ObjectUtil.isNotNull(retBody)) {
                List<EmsTrackVO> trackList = JSONArray.parseArray(JSON.toJSONString(retBody.get("responseItems")), EmsTrackVO.class);
                return ResponseDTO.succData(trackList);
            }
        }
        return ResponseDTO.wrap(500,"快递记录查询接口调用异常");
    }
}
